<?php
/**
 * 文件缓存类
 * 尽量不要不修改缓存，性能很差
 * User: cory
 * Date: 2017/3/17
 * Time: 13:58
 */
class CacheFile implements CacheInterface{
    private $file_path = ''; //缓存目录
    private $file_name = 'language_file_cache.php';
    private $cache_sign = '';//缓存标识，用来标志相应的语言缓存

    public function set($key,$val){
        $lang_array = $this->get_lang_cache();
        $lang_array[$key] = $val;
        return $this->set_all($lang_array);
    }

    /**
     * 批量载入
     */
    public function set_all($lang_words,$cache_sign = ''){
        $write = '<?php return ';
        $write .= var_export($lang_words,true);
        $write .= ';';
        return file_put_contents($this->get_file_path(),$write);
    }

    /**
     * 得到缓存数据
     * @param $key 
     * @return mixed
     */
    public function get($key){
        $lang_array = $this->get_lang_cache();
        if(empty($lang_array)){
            return false;
        }
        return $lang_array[$key];
    }

    /**
     * 删除缓存
     * @param $key
     * @return int
     */
    public function remove($key){
        $lang_array = $this->get_lang_cache();
        unset($lang_array[$key]);
        return $this->set_all($lang_array);
    }

    /** 初始化
     * @param $config_array
     * @return bool
     */
    public function connect($config_array,$lang){
        $this->file_path = $_SERVER['DOCUMENT_ROOT'].'/'.$config_array['path'];
        $this->cache_sign = $lang;
        return file_exists($this->file_path);
    }

    /**
     * 关闭连接
     */
    public function close(){

    }

    /**获取缓存信息
     * @return mixed
     */
    private function get_lang_cache(){
        $path =  $this->get_file_path();
        if(file_exists($path)){
            return require $path;
        }else{
            return false;
        }
    }

    /**
     * 返回缓存文件目录
     */
    private function get_file_path(){
        return $this->file_path.'/'.$this->cache_sign.'_'.$this->file_name;
    }
}